package obecto.manager.dragManager
{
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.TouchEvent;
	
	public class DragManager
	{
		[Bindable] public var isDraging : Boolean;
		
		private static var _instance : DragManager;
		public static function get instance():DragManager
		{
			if(!_instance)
			{
				_instance = new DragManager();
			}
			return _instance;
		}
		
		public var dragProxy : DragProxy;
		
		private var stage : Stage;
		
		public function acceptDragDrop(target : DisplayObject) : void
		{
			dragProxy.target = target;
		}
		
		public function startDrag(dragInitiator:DisplayObject, 
                                  dragSource:Object, 
                                  dragImage:DisplayObject = null,
                                  offsetX:Number = 0,
                                  offsetY:Number = 0,
                                  originOffsetX:Number = 0,
                                  originOffsetY:Number = 0,
                                  returnX:Number = NaN,
                                  returnY:Number = NaN,
                                  returnOnCancel:Boolean = true,
                                  touchEvent:TouchEvent = null,
                                  returnScaleX:Number = 1,
                                  returnScaleY:Number = 1) : DragProxy
		{
			isDraging = true;
			
			stage = dragInitiator.stage;
			
			if(isNaN(returnX))
			{
				returnX = stage.mouseX;
			}
			if(isNaN(returnY))
			{
				returnY = stage.mouseY;
			}
			
			dragProxy = new DragProxy(stage.mouseX, stage.mouseY, 
				                      offsetX, offsetY, 
									  originOffsetX, originOffsetY, 
									  returnX, returnY, returnOnCancel, 
									  returnScaleX, returnScaleY);
			
			if(dragImage)
			{
				dragProxy.addChild(dragImage);
			}
			
			dragProxy.dragSource = dragSource;	
			dragProxy.dragInitiator = dragInitiator;
			
			stage.addChild(dragProxy);
			
			if(touchEvent)
			{
				dragProxy.startTouchDrag(touchEvent.touchPointID);
			}
			else
			{
				dragProxy.startDrag();
			}
			
			return dragProxy;
		}
		
		public function stopDrag() : void
		{
			if(dragProxy)
			{
				cleanUp();
			}
			
			isDraging = false;
		}
		
		private function cleanUp() : void
		{
			if(dragProxy.parent)
			{
				dragProxy.parent.removeChild(dragProxy);
				dragProxy = null;
			}		
		}
	}
}